package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//每次请求登录状态校验
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //仅仅是在进入controller之前进行拦截判断
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        //1.查看session中是否有我们指定的用户对象
        Employee employee = (Employee) request.getSession().getAttribute("employee_info");

        if (employee != null) {
            //2. 代表session存在,也就是用户处于登录状态,放行请求即可

            //将用户信息放入到ThreadLocal
            EmployeeHolder.set(employee);


            return true;
        } else {
            //3. 代表session不存在,
            // 3-1 告诉前端页面,当前用户未登录
            ResultInfo info = ResultInfo.error("not login");
            String json = new ObjectMapper().writeValueAsString(info);
            response.getWriter().write(json);

            //3-2禁止通行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除ThreadLocal中当卡线程的信息
        EmployeeHolder.remove();
    }
}
